// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Author: wsfuyibing <682805@qq.com>
// Date: 2024-12-18

package middlewares

import (
	"context"
	"gitee.com/go-libs/log"
	"gitee.com/go-libs/perm"
	"gitee.com/go-libs/result"
	"gitee.com/go-wares/framework-iris/framework/src/middlewares"
	"github.com/kataras/iris/v12"
	"gomq/app/authorizer"
	"gomq/app/errs"
)

// PermissionMiddleware verify user permission. Return forbidden if fail to
// verify.
func PermissionMiddleware(i iris.Context) {
	var (
		auth          = authorizer.New()
		authorization *authorizer.Authentication
		ctx           context.Context
		resource      = perm.Resource(i.Request().URL.Path)
		yes           bool
	)

	// Inherit request context for the same tracing.
	if span, ok := i.Values().Get(middlewares.TracingSpan).(log.Span); ok {
		ctx = span.GetContext()
	} else {
		ctx = i.Request().Context()
	}

	// Verify user permission by bound roles with resource.
	if authorization, yes = auth.Get(i); yes {
		if verification := auth.PermissionContainer().Verify(resource, authorization.Roles...); verification.Success() {
			log.Infofc(ctx, `[middleware=permission] permission verified: resource="%s", roles=%v`, resource, authorization.Roles)
			i.Next()
			return
		}
	}

	// Access denied.
	log.Infofc(ctx, `[middleware=permission] access denied: resource="%s"`, resource)
	_ = i.JSON(result.New().WithError(errs.ErrUserInvalidAuthorization))
}
